export const state = () => ({
  orderType: 1, // 订单类型：1：批发订单 2: 寄售订单
  productAddList: [] // 产品需求清单
})

export const mutations = {
  // 更新订单类型
  updateOrderType (state, type) {
    state.orderType = type
  },
  // 向需求清单添加商品(仅添加)
  addProductToList (state, product) {
    state.productAddList.unshift({ ...product })
  },
  // 重置商品列表
  resetProductToList (state) {
    state.productAddList = []
  },
  // 更新其中一条数据数量（已生产需求清单增减报错问题）
  changeListItemNum (state, data) {
    state.productAddList[ data.index ].amount = data.num
  }
}

export const actions = {
  updateProductList ({ state, commit }, row) {
    // 已经添加，更新操作，否则，新增
    const len = state.productAddList.length
    if (len) {
      const list = state.productAddList.slice()
      const index = list.findIndex(item => Object.is(row.id, item.id))

      if (index > -1) {
        commit('changeListItemNum', { index, num: parseInt(list[ index ].amount) + parseInt(row.amount) })
        return
      }
    }

    commit('addProductToList', row)
  }
}
